import pytest
import time
import requests
from lib.config import config
from lib.sqldbconnn import sqlconn
from lib.http_client import http_client
from lib.logger import Logger


@pytest.fixture
def fixture_login_register_and_delete():
    ## 注册账号
    name = "test_" + str(time.time())
    password = "1234"
    data = {
        "name": name,
        "password1": password,
        "password2": password
    }
    r = requests.request(method="post", url=config["url"]["register"], json=data)
    assert r.status_code == 200
    assert r.json()["code"] == "200", "json中code字段的值应该是'200'"
    yield name, password
    ## 删除注册账号
    deleteRegisterSql(name)


@pytest.fixture
def fixture_register_delete():
    name = "test_" + str(time.time())
    yield name
    deleteRegisterSql(name)

## 创建到货通知书
@pytest.fixture
def fixture_insert_asn_order():
    logger=Logger()
    ## 注册账号
    name = "test_" + str(time.time())
    password = "1234"
    path = "/register/"
    data = {
        "name": name,
        "password1": password,
        "password2": password
    }
    client=http_client()
    conn=sqlconn()
    r=client.request(path=path, method="post", json=data)
    token=r.json()["data"]["openid"]
    operator = str(r.json()["data"]["user_id"])
    ## 更新请求头
    data={
        "operator": operator,
        "token": token,
    }
    client.updateHeaders(data)
    assert r.json()["code"] == "200"
    yield logger,client,conn,name,password
    ##  清除注册
    deleteRegisterSql(name)



## 根据名字删除注册账号
def deleteRegisterSql(name):
    sql1 = f'delete from user_profile where name ="{name}"'
    sql2 = f'delete from auth_user where username ="{name}"'
    sql_list = [sql1, sql2]
    sqlconn().sql_execute(sql_list)
